package com.qf.smsplatfrom.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.smsplatfrom.annotations.DescribeAnno;
import com.qf.smsplatfrom.cache.DescribeCaChe;
import com.qf.smsplatfrom.cache.TSmsTemplateCache;
import com.qf.smsplatfrom.constans.ResultCode;
import com.qf.smsplatfrom.controller.swagger.MyProceedingJoinPoint;
import com.qf.smsplatfrom.events.TSmsTemplateEvens;
import com.qf.smsplatfrom.exceptions.PhoneBaseException;
import com.qf.smsplatfrom.mapper.TSmsTemplateMapper;
import com.qf.smsplatfrom.pojo.*;
import com.qf.smsplatfrom.service.TSmsTemplateService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class TSmsTemplateServiceImpl implements TSmsTemplateService {
    private TSmsTemplateMapper tSmsTemplateMapper;
    private TSmsTemplateCache tSmsTemplateCache;
    private ApplicationContext context;
    private DescribeCaChe describeCaChe;


    @Autowired
    public void setDescribeCaChe(DescribeCaChe describeCaChe) {
        this.describeCaChe = describeCaChe;
    }

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void settSmsTemplateCache(TSmsTemplateCache tSmsTemplateCache) {
        this.tSmsTemplateCache = tSmsTemplateCache;
    }

    @Autowired
    public void settSmsTemplateMapper(TSmsTemplateMapper tSmsTemplateMapper) {
        this.tSmsTemplateMapper = tSmsTemplateMapper;
    }


    @Override
    public void addTemplate(TSmsTemplate tSmsTemplate) {
        if (tSmsTemplate.isNull(CheckType.ADD)) {
            throw new PhoneBaseException("传递的数据不可为空", ResultCode.NO_PERMISSON);
        }
        tSmsTemplateMapper.insertTSmsTemplate(tSmsTemplate);
        context.publishEvent(new TSmsTemplateEvens());
    }

    @Override
    public PageInfo<TSmsTemplate> showAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TSmsTemplate> allData = tSmsTemplateCache.getAllData();
        MyAuthUser principal = (MyAuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        //Object user = ((ServletRequestAttributes) requestAttributes).getRequest().getSession().getAttribute("user");
        List<TSmsTemplate> collect = allData.stream().filter(tSmsTemplate -> {
            return tSmsTemplate.getOwntype() == 1 || tSmsTemplate.getCreater() == principal.getId() || principal.getType() == 1;
        }).collect(Collectors.toList());
        List<TSmsTemplate> tSmsTemplates = collect.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<TSmsTemplate> pageInfo = new PageInfo<>(tSmsTemplates);
        return pageInfo;
    }

    @Override
    public PageInfo<TSmsTemplate> findByMultiParam(TSmsTemplate tSmsTemplate,Integer pageNum,Integer pageSize) throws InstantiationException, IllegalAccessException {
        Class<? extends TSmsTemplate> aClass = tSmsTemplate.getClass();//获得一个反射对象

        Field[] fields = aClass.getDeclaredFields();//获取所有的类属性名
        List<String> splits = new ArrayList<>();//新建一个list集合，专门存放过滤后的属性名称

        for (Field field : fields) {//for循环
            String name = field.getName();//获取每一个属性名
            TDescribe byKey = describeCaChe.getByKey(name);//分别查找
            if (byKey == null) {//判断状态
                continue;//跳过此次循环
            }
            if (byKey.getState() == 0) {//判断状态
                continue;
            }
            splits.add(byKey.getList());//添加几何数据
        }

        TSmsTemplate instance = aClass.newInstance();//通过反射创建一个新对象
        splits.forEach(name -> {
            //从传递的参数据对象中取出来我们需要的参数,设置给我们新创建的对象
            try {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, aClass);//从指定类中获取指定方法的属性
                Method readMethod = propertyDescriptor.getReadMethod();//读方法 就是 get 方法
                Method writeMethod = propertyDescriptor.getWriteMethod();//写方法就是 set 方法
                writeMethod.invoke(instance, readMethod.invoke(tSmsTemplate));
            } catch (IntrospectionException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        });

        PageHelper.startPage(pageNum,pageSize);
        List<TSmsTemplate> smsTemplates = tSmsTemplateMapper.findByMultiParam(instance);

        MyAuthUser principal = (MyAuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<TSmsTemplate> collect = smsTemplates.stream().filter(tSmsTemplate1 -> {
            return tSmsTemplate1.getOwntype() == 1 || tSmsTemplate1.getCreater() == principal.getId() || principal.getType() == 1;
        }).collect(Collectors.toList());

        List<TSmsTemplate> templates = collect.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<TSmsTemplate> pageInfo = new PageInfo<>(templates);
        return pageInfo;
    }
}
